<template>
  <div class="private-message-management">
    <div class="header">
      <h2> </h2>
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索会话用户"
          style="width: 200px; margin-right: 10px;"
          clearable
          @clear="fetchChatList"
          @keydown.enter="fetchChatList"
        >
          <template #append>
            <el-button :icon="Search" @click="fetchChatList" />
          </template>
        </el-input>
        <el-button type="success" @click="fetchChatList" :loading="loading">刷新</el-button>
      </div>
    </div>
    
    <div class="content-container">
      <!-- 会话列表 -->
      <div class="chat-list-container">
        <div class="chat-list-header">
          <h3>会话列表</h3>
        </div>
        <div class="chat-list" v-loading="loading">
          <div 
            v-for="chat in chatList" 
            :key="chat.chat_id"
            class="chat-item"
            :class="{ active: currentChat?.chat_id === chat.chat_id }"
            @click="selectChat(chat)"
          >
            <el-avatar 
              :size="40" 
              :src="chat.user?.avatar"
            >
              {{ chat.user?.name?.charAt(0) || '?' }}
            </el-avatar>
            <div class="chat-info">
              <div class="chat-name">{{ chat.user?.name || '未知用户' }} - {{ chat.other_user?.name || '未知用户' }}</div>
              <div class="chat-time">{{ formatDate(chat.updatedAt) }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 消息详情 -->
      <div class="message-detail-container">
        <div v-if="currentChat" class="message-header">
          <el-avatar 
            :size="40" 
            :src="currentChat.user?.avatar"
          >
            {{ currentChat.user?.name?.charAt(0) || '?' }}
          </el-avatar>
          <div class="user-info">
            <div class="user-name">{{ currentChat.user?.name || '未知用户' }} - {{ currentChat.other_user?.name || '未知用户' }}</div>
          </div>
          <div class="message-header-actions">
            <el-button type="danger" size="small" @click="handleDeleteChat">删除会话</el-button>
          </div>
        </div>
        
        <div v-else class="no-chat-selected">
          <el-empty description="请选择一个会话" />
        </div>
        
        <div 
          v-if="currentChat" 
          class="message-list" 
          ref="messageListRef"
        >
          <div 
            v-for="message in messageList" 
            :key="message.message_id"
            class="message-item"
            :class="{ 
              sent: message.sender_id !== currentChat?.other_user?.user_id, 
              received: message.sender_id === currentChat?.other_user?.user_id 
            }"
          >
            <div class="message-content">
              <div class="message-text">{{ message.content }}</div>
              <div class="message-time">{{ formatTime(message.createdAt) }}</div>
              <div class="message-actions" v-if="currentChat">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="handleEditMessage(message)"
                  link
                >
                  编辑
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleDeleteMessage(message)"
                  link
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
        
        <div v-if="currentChat" class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.limit"
            :page-sizes="[50, 500, 1000]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
  
  <!-- 编辑消息对话框 -->
  <el-dialog
    v-model="editMessageVisible"
    title="编辑消息"
    width="500px"
  >
    <el-input
      v-model="editMessageContent"
      type="textarea"
      :rows="4"
      placeholder="请输入消息内容"
    />
    <template #footer>
      <el-button @click="editMessageVisible = false">取消</el-button>
      <el-button type="primary" @click="submitMessageEdit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import type { PrivateChat, PrivateMessage } from '@/api/modules/message'
import { 
  getPrivateChatList, // 改为使用非分页接口
  getPrivateMessageHistory,
  deletePrivateChat,
  deletePrivateMessage,
  updatePrivateMessage
} from '@/api/modules/message'

// 会话列表
const chatList = ref<PrivateChat[]>([])

// 当前选中的会话
const currentChat = ref<PrivateChat | null>(null)

// 消息列表
const messageList = ref<PrivateMessage[]>([])

// 加载状态
const loading = ref(false)

// 搜索关键词
const searchKeyword = ref('')

// 移除会话列表分页信息
// 消息分页信息
const pagination = ref({
  page: 1,
  limit: 50,
  total: 0
})

// 消息列表容器引用
const messageListRef = ref<HTMLDivElement | null>(null)

// 编辑消息相关的状态
const editingMessage = ref<PrivateMessage | null>(null)
const editMessageContent = ref('')
const editMessageVisible = ref(false)

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const now = new Date();
  
  // 如果是今天，只显示时间
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  
  // 如果是今年，显示月日和时间
  if (date.getFullYear() === now.getFullYear()) {
    return date.toLocaleDateString('zh-CN', { 
      month: 'short', 
      day: 'numeric',
      hour: '2-digit', 
      minute: '2-digit' 
    });
  }
  
  // 其他情况显示完整日期
  return date.toLocaleDateString('zh-CN');
};

// 格式化时间（只显示时间）
const formatTime = (dateString: string) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
};

// 获取会话列表
const fetchChatList = async () => {
  loading.value = true
  try {
    // 使用非分页接口
    const response = await getPrivateChatList({
      keyword: searchKeyword.value || undefined
    })
    
    chatList.value = response.data || []
    
    // 如果当前没有选中会话且有会话列表，默认选中第一个
    if (!currentChat.value && chatList.value.length > 0) {
      selectChat(chatList.value[0])
    }
  } catch (error) {
    console.error('获取会话列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 移除会话列表分页相关的方法
// 处理消息分页大小变化
const handleSizeChange = (val: number) => {
  pagination.value.limit = val
  pagination.value.page = 1 // 重置到第一页
  fetchMessageHistory()
}

// 处理消息当前页变化
const handleCurrentChange = (val: number) => {
  pagination.value.page = val
  fetchMessageHistory()
}

// 选择会话
const selectChat = async (chat: PrivateChat) => {
  currentChat.value = chat
  
  // 重置分页
  pagination.value.page = 1
  pagination.value.total = 0
  
  // 获取消息历史
  await fetchMessageHistory()
  
  // 滚动到消息底部
  scrollToBottom()
}

// 获取消息历史
const fetchMessageHistory = async () => {
  if (!currentChat.value) return;
  
  loading.value = true
  try {
    const response = await getPrivateMessageHistory({
      chat_id: currentChat.value.chat_id,
      page: pagination.value.page,
      limit: pagination.value.limit
    })
    
    messageList.value = response.data?.messages || []
    pagination.value.total = response.data?.pagination?.total || 0
    
    // 消息按时间顺序排列（最新的在底部）
    if (messageList.value) {
      messageList.value.reverse()
    }
  } catch (error) {
    console.error('获取消息历史失败:', error)
  } finally {
    loading.value = false
  }
}

// 滚动到消息底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageListRef.value) {
      messageListRef.value.scrollTop = messageListRef.value.scrollHeight
    }
  })
}

// 组件挂载时获取会话列表
onMounted(() => {
  fetchChatList()
})

// 处理删除会话
const handleDeleteChat = async () => {
  if (!currentChat.value) return;
  
  try {
    await deletePrivateChat({ chat_id: currentChat.value.chat_id });
    ElMessage.success('会话删除成功');
    currentChat.value = null;
    messageList.value = [];
    await fetchChatList();
  } catch (error) {
    console.error('删除会话失败:', error);
  }
}

// 处理编辑消息
const handleEditMessage = (message: PrivateMessage) => {
  editingMessage.value = message;
  editMessageContent.value = message.content;
  editMessageVisible.value = true;
}

// 处理删除消息
const handleDeleteMessage = async (message: PrivateMessage) => {
  try {
    await deletePrivateMessage({ message_id: message.message_id });
    ElMessage.success('消息删除成功');
    // 重新获取消息列表
    await fetchMessageHistory();
  } catch (error) {
    console.error('删除消息失败:', error);
  }
}

// 提交消息编辑
const submitMessageEdit = async () => {
  if (!editingMessage.value) return;
  
  try {
    const updatedMessage = await updatePrivateMessage({ 
      message_id: editingMessage.value.message_id, 
      content: editMessageContent.value 
    });
    ElMessage.success('消息编辑成功');
    editMessageVisible.value = false;
    // 更新消息列表中的内容
    const index = messageList.value.findIndex(msg => msg.message_id === editingMessage.value!.message_id);
    if (index !== -1) {
      messageList.value[index] = updatedMessage.data;
    }
  } catch (error) {
    console.error('编辑消息失败:', error);
  }
}
</script>

<style scoped>
.private-message-management {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.content-container {
  display: flex;
  flex: 1;
  gap: 20px;
  overflow: hidden;
}

.chat-list-container {
  width: 300px;
  display: flex;
  flex-direction: column;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.chat-list-header {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.chat-list-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.chat-list {
  flex: 1;
  overflow-y: auto;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  cursor: pointer;
  border-bottom: 1px solid #f5f7fa;
  transition: background-color 0.2s;
}

.chat-item:hover {
  background-color: #f5f7fa;
}

.chat-item.active {
  background-color: #ecf5ff;
}

.chat-info {
  margin-left: 12px;
  flex: 1;
  min-width: 0;
}

.chat-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-time {
  font-size: 12px;
  color: #909399;
}

.message-detail-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.message-header {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.user-info {
  margin-left: 12px;
}

.user-name {
  font-size: 16px;
  font-weight: 500;
}

.message-header-actions {
  margin-left: auto;
}

.message-actions {
  margin-top: 5px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.message-actions .el-button {
  padding: 0;
}

.no-chat-selected {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #fafafa;
}

.message-item {
  display: flex;
  margin-bottom: 15px;
}

.message-item.received {
  justify-content: flex-start;
}

.message-item.sent {
  justify-content: flex-end;
}

.message-content {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 8px;
  position: relative;
}

.message-item.received .message-content {
  background-color: white;
  border: 1px solid #ebeef5;
}

.message-item.sent .message-content {
  background-color: #409eff;
  color: white;
}

.message-text {
  word-wrap: break-word;
  word-break: break-word;
  white-space: pre-wrap;
}

.message-time {
  font-size: 12px;
  margin-top: 5px;
  text-align: right;
}

.message-item.received .message-time {
  color: #909399;
}

.message-item.sent .message-time {
  color: rgba(255, 255, 255, 0.8);
}

</style>